import { nextTick } from "vue";
import type { RouteRecordRaw } from "vue-router";
import NProgress from "@/utils/nprogress";
import { getAppToken, getToken } from "@/utils/auth";
import router from "@/router";
import { usePermissionStore, useUserStore } from "@/store";

// 提取 NProgress.done() 为公用方法
function closeNProgress() {
  NProgress.done();
}

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/login"];
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const token: string = getToken();
    const appToken: string = getAppToken();

    if (!appToken && (to.path === "/applicationCenter" || to.path === "/modifyPassword") && token) {
      next();
      return;
    }

    if (appToken) {
      if (to.path === "/login") {
        next({ path: "/" });
        return;
      }

      const permissionStore = usePermissionStore();
      if (permissionStore.isRoutesLoaded) {
        if (to.matched.length === 0) {
          next("/404");
        } else {
          const title = (to.params.title as string) || (to.query.title as string);
          if (title) {
            to.meta.title = title;
          }
          next();
        }
      } else {
        try {
          const dynamicRoutes = await permissionStore.generateRoutes();
          dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
          await nextTick(); // 确保 DOM 更新
          next({ ...to, replace: true });
        } catch (error) {
          console.error(error);
          await useUserStore().clearUserData();
          next("/login");
          closeNProgress();
        }
      }
    } else {
      if (to.path === "/login" && token) {
        next({ path: "/applicationCenter" });
        closeNProgress();
        return;
      }

      if (whiteList.includes(to.path)) {
        next();
      } else {
        next({ path: "/login" });
        closeNProgress();
      }
    }
  });

  // 后置守卫，保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    closeNProgress();
  });
}
